<template>
  <!-- 搜索条件 -->
  <el-card v-show="showQueryForm" class="form-card">
    <QueryForm ref="queryFormRef" :form-data="queryFormData" :items="queryFormItems" :model="queryFormData" :show-control="true" label-width="82px">

      <QueryFormItem label="状态标识">
        <MultipleSelect v-model="specialFlagList" :options="specialFlagOptions" placeholder="请选择状态标识"/>
      </QueryFormItem>

      <template #control>
        <el-button icon="Search" type="info" @click="handleSearch">{{ $t('form.search') }}</el-button>
        <el-button icon="Refresh" @click="handleResetQueryForm">{{ $t('form.reset') }}</el-button>
      </template>
    </QueryForm>
  </el-card>

  <!-- 列表数据 -->
  <el-card class="content-card system-user">
    <!-- 工具栏 -->
    <table-toolbar v-model:columns="columns"
                   v-model:show-query-form="showQueryForm"
                   v-model:size="size"
                   v-model:stripe="stripe"
                   @refresh="handleSearch">
      <!-- 操作区域 -->
      <el-button v-permission="'user:pyramid:calculate'" icon="upload" plain type="danger" @click="handleBatchCalculateTeamInfo">
        {{ multipleSelection.length > 0 ? `批量计算(${multipleSelection.length})` : '批量计算' }}
      </el-button>
      <el-button v-permission="'user:pyramid:calculate'" icon="promotion" plain type="primary" @click="handleContributionReleaseCheck">贡献值释放</el-button>
    </table-toolbar>

    <!-- 列表记录 -->
    <div class="table-wrapper">
      <!-- 列表数据 -->
      <el-table ref="tableRef"
                v-loading="loading"
                :data="tableData"
                :row-key="rowKey"
                :size="size"
                :stripe="stripe"
                show-overflow-tooltip
                @select="handleSelectChange"
                @select-all="handleSelectAll"
                @sort-change="handleSortChange">
        <template #empty>
          <el-empty class="table-empty" description="暂无数据"/>
        </template>

        <table-column :columns="columns">
          <template #user_id="scope">
            <UserInfoLink :user-id="scope.row.user_id"/>
          </template>

          <template #parent_id="scope">
            <UserInfoLink :user-id="scope.row.parent_id"/>
          </template>

          <template #user_level="scope">
            <div @click="handleModifyUserLevel(scope.row)">
              <DictTag v-model="scope.row.user_level" :circle="false" dict-type="user_level"/>
            </div>
          </template>

          <template #private_level="scope">
            <div @click="handleModifyPrivateLevel(scope.row)">
              <DictTag v-model="scope.row.private_level" :circle="false" dict-type="private_level"/>
            </div>
          </template>

          <template #special_flag="scope">
            <MultipleTag :flag-val="scope.row.special_flag" :options="specialFlagOptions" default-name=""/>
          </template>

          <template #operations="scope">
            <el-space :size="1" :spacer="spacer">
              <el-button v-permission="'user:pyramid:info'" link type="info" @click="handleShowPyramidInfo(scope.row.user_id)">查看</el-button>
              <el-button v-permission="'user:pyramid:calculate'" link type="primary" @click="handleCalculateTeamInfo(scope.row.account)">计算</el-button>
            </el-space>
          </template>
        </table-column>
      </el-table>

      <!-- 分页操作 -->
      <el-pagination v-if="totalCount > 0"
                     :current-page="pageQuery.pageNum"
                     :page-size="pageQuery.pageSize"
                     :page-sizes="pageSizes"
                     :total="totalCount"
                     background
                     class="table-pagination"
                     layout="total, sizes, prev, pager, next"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"/>
    </div>
  </el-card>

  <!-- 团队关系 -->
  <UserPyramidInfo ref="pyramidRef"/>
</template>

<script lang="tsx" setup>
import { computed, h, onBeforeMount, reactive, ref } from 'vue';
import { QueryForm, QueryFormItem } from '@/components/query-form';
import useLoading from '@/hooks/use-loading';
import TableColumn, { TableColumnData } from '@/components/table-column/index.vue';
import TableToolbar from '@/components/table-toolbar/index.vue';
import useTableSelection from '@/hooks/use-table-selection';
import { ElDivider, ElLoading, ElMessage, ElMessageBox, ElNotification, TableInstance } from 'element-plus';
import useTable from '@/hooks/use-table.ts';
import { computedOperateWidth, toDecimal } from '@/utils';
import { hasPermission } from '@/utils/permission.ts';
import { QueryFormItemRule } from '@/components/query-form/constants.ts';
import { batchCalculateTeamInfo, calculateTeamInfo, contributionReleaseCheck, modifyPrivateLevel, modifyUserLevel, userPyramidList } from '@/api/api-user.ts';
import { MultipleSelect, MultipleTag } from '@/components/other';
import { UserInfoLink } from '@/components/user-info-link';
import { specialFlagOptions } from '@/utils/global-dict.ts';
import UserPyramidInfo from '@/views/user/pyramid/team-info.vue';
import { DictTag } from '@/components/dict-tag';

const spacer = h(ElDivider, {direction: 'vertical'});

// 查询
const queryFormData = reactive({
  user_id: undefined,
  account: undefined,
  parent_id: undefined,
  parent_account: undefined,
  special_flag: undefined,
  account_flag: undefined,
  user_level: undefined,
  private_level: undefined,
});
const queryFormRef = ref<InstanceType<typeof QueryForm>>();
const queryFormItems = ref<QueryFormItemRule[]>([
  {type: 'input', prop: 'user_id', label: '用户编号', placeholder: '请输入用户编号', clearable: true},
  {type: 'input', prop: 'account', label: '用户账号', placeholder: '请输入用户账号', clearable: true,},
  {type: 'input', prop: 'parent_id', label: '邀请人编号', placeholder: '请输入邀请人编号', clearable: true,},
  {type: 'input', prop: 'parent_account', label: '邀请人账号', placeholder: '请输入邀请人账号', clearable: true,},
  {type: 'dict-select', prop: 'user_level', label: '用户级别', placeholder: '请选择用户级别', dictType: 'user_level', clearable: true,},
  {type: 'dict-select', prop: 'private_level', label: '私域级别', placeholder: '请选择私域级别', dictType: 'private_level', clearable: true,},
]);
const pickerDate = ref([]);
const specialFlagList = ref<Number[]>([]);

// 列表相关
const tableRef = ref<TableInstance>();
const tableData = ref<any[]>([]);
const totalCount = ref(0);

// 操作区域宽度计算
const operateWidth = computed(() => {
  let count = 0
  if (hasPermission('user:pyramid:info')) count += 1
  if (hasPermission('user:pyramid:calculate')) count += 1
  return computedOperateWidth(count);
})

// 列设置
const columns = ref<TableColumnData[]>([
  {type: 'selection', width: 45, hidden: !hasPermission('user:pyramid:calculate')},
  {prop: 'uid', label: 'UID', width: 120, align: 'center', sortable: 'custom'},
  {prop: 'user_id', label: '用户编号', width: 125, align: 'center', sortable: 'custom'},
  {prop: 'account', label: '用户账号', minWidth: 160, align: 'center', sortable: 'custom'},
  {prop: 'parent_id', label: '邀请人编号', width: 125, align: 'center', sortable: 'custom'},
  {prop: 'parent_account', label: '邀请人账号', minWidth: 160, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'tier_level', label: '层级', width: 100, align: 'center', sortable: 'custom'},
  {prop: 'user_level', label: '用户级别', width: 120, align: 'center', sortable: 'custom'},
  {prop: 'private_level', label: '私域级别', width: 120, align: 'center', sortable: 'custom'},
  {prop: 'balance', label: '余额', width: 130, align: 'right', sortable: 'custom', render: (scope, val) => <span>{toDecimal(val, 4)}</span>},
  {prop: 'subsidy_xs', label: '线上补贴', width: 130, align: 'right', sortable: 'custom', render: (scope, val) => <span>{toDecimal(val, 4)}</span>},
  {prop: 'subsidy_xx', label: '线下补贴', width: 130, align: 'right', sortable: 'custom', render: (scope, val) => <span>{toDecimal(val, 4)}</span>},
  {prop: 'bonus_zj', label: '创客奖金', width: 130, align: 'right', sortable: 'custom', render: (scope, val) => <span>{toDecimal(val, 4)}</span>},
  {prop: 'bonus_hhr', label: '合伙人奖励', width: 130, align: 'right', sortable: 'custom', render: (scope, val) => <span>{toDecimal(val, 4)}</span>},
  {prop: 'bonus_extra', label: '额外奖励', width: 130, align: 'right', sortable: 'custom', render: (scope, val) => <span>{toDecimal(val, 4)}</span>},
  {prop: 'contribution_value', label: '贡献值余额', width: 130, align: 'right', sortable: 'custom', render: (scope, val) => <span>{toDecimal(val, 4)}</span>},
  {prop: 'contribution_total', label: '累计贡献值', width: 130, align: 'right', sortable: 'custom', render: (scope, val) => <span>{toDecimal(val, 4)}</span>},
  {prop: 'special_flag', label: '状态标识', minWidth: 220, align: 'left', headerAlign: 'center', sortable: 'custom'},
  {prop: 'team_count', label: '团队人数', minWidth: 110, align: 'center', sortable: 'custom'},
  {prop: 'team_certify_count', label: '团队实名', minWidth: 110, align: 'center', sortable: 'custom'},
  {prop: 'team_valid_count', label: '团队有效', minWidth: 110, align: 'center', sortable: 'custom'},
  {prop: 'directly_count', label: '直推人数', minWidth: 110, align: 'center', sortable: 'custom'},
  {prop: 'directly_certify_count', label: '直推实名', minWidth: 110, align: 'center', sortable: 'custom'},
  {prop: 'directly_valid_count', label: '直推有效', minWidth: 110, align: 'center', sortable: 'custom'},
]);

onBeforeMount(() => {
  if (operateWidth.value > 0) {
    columns.value.push({prop: 'operations', label: '操作', fixed: 'right', width: operateWidth.value, align: 'left', headerAlign: 'center'},)
  }
});

const rowKey = ref('user_id');
const [loading, setLoading] = useLoading(false);
const {tableMethods, tableState} = useTable(() => fetchDataList(), queryFormRef, true);
const {size, stripe, showQueryForm, pageQuery, pageSizes} = tableState
const {handleSizeChange, handleCurrentChange, handleSortChange, handleResetForm} = tableMethods
const {handleSelectChange, handleSelectAll, multipleSelection} = useTableSelection(tableData, tableRef, rowKey.value);

// 数据查询
const fetchDataList = async () => {
  setLoading(true);
  try {
    // 处理其他查询参数
    handleOtherQueryParams();
    // 查询数据
    const {data} = await userPyramidList({
      page_num: pageQuery.pageNum,
      page_size: pageQuery.pageSize,
      order_mode: pageQuery.orderMode,
      order_column: pageQuery.orderColumn,
      ...queryFormData,
    });
    // 结果转换
    tableData.value = data.list;
    totalCount.value = data.pages.total_count;
  } catch (err) {
  } finally {
    setLoading(false);
  }
};

// 刷新数据
const handleSearch = () => {
  fetchDataList();
};

// 重置查询条件
const handleResetQueryForm = () => {
  pickerDate.value = [];
  specialFlagList.value = [];
  handleResetForm();
};

// 处理其他查询条件
const handleOtherQueryParams = () => {
  // 特殊状态标识参数
  let specialFlag = 0
  // @ts-ignore
  specialFlagList.value.forEach(it => specialFlag |= it)
  // @ts-ignore
  queryFormData.special_flag = specialFlag > 0 ? specialFlag : undefined
}

/** 团队信息 */
const pyramidRef = ref<any>()
const handleShowPyramidInfo = (id: number) => {
  pyramidRef.value?.open(id);
};

/** 团队信息计算 */
const handleCalculateTeamInfo = (account: string) => {
  ElMessageBox({
    title: '提示',
    message: h('p', null, ['是否确认对账号 ', h('span', {style: 'font-weight: bold'}, account), ' 的用户进行团队计算操作吗？',]),
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '放弃',
  }).then((action) => {
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    calculateTeamInfo({account: account}).then(() => {
      // 提示信息
      ElNotification({title: '成功', message: '已提交到队列中进行操作', type: 'success', duration: 2000})
    }).finally(() => loading.close())
  }).catch(() => {

  });
};

/** 批量团队信息计算 */
const handleBatchCalculateTeamInfo = () => {
  if (!multipleSelection.value.length) {
    ElMessage.error('请选择需要重新计算团队信息的用户');
    return;
  }
  // 需要计算的用户编号
  const item_ids = multipleSelection.value.map((item) => {
    return item.user_id;
  });

  // 弹窗确认提示
  ElMessageBox({
    title: '提示',
    message: h('p', null, ['您确定对选中的 ', h('span', {style: 'font-weight: bold'}, item_ids.length), ' 个用户进行团队计算操作吗？',]),
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '放弃',
  }).then((action) => {
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    batchCalculateTeamInfo({user_ids: item_ids}).then(() => {
      // 提示信息
      ElNotification({title: '成功', message: '已提交到队列中进行操作', type: 'success', duration: 2000})
    }).finally(() => loading.close())
  }).catch(() => {

  });
};

/** 用户级别修改 */
const handleModifyUserLevel = (item: any) => {
  if (item == null || item.id <= 0) return
  if (!hasPermission('api:user:modify_level')) return

  // 弹窗提示
  ElMessageBox.prompt(h('p', null, ['是否修改账号 ', h('span', {style: 'font-weight: bold'}, item.account), ' 的 用户级别 操作吗？',]), '提示', {
    type: 'warning',
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '请输入新的用户级别',
    inputPattern: /^[0-9]*$/,
  }).then(({value}) => {
    let newValue = parseInt(value) || 0
    if (newValue < 0) {
      ElMessage.error('请输入正确的等级');
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    modifyUserLevel({account: item.account, level: newValue}).then(() => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 刷新列表数据
      handleSearch();
    }).finally(() => loading.close())
  }).catch(() => {

  });
};

/** 私域级别修改 */
const handleModifyPrivateLevel = (item: any) => {
  if (item == null || item.id <= 0) return
  if (!hasPermission('api:user:modify_level')) return

  // 弹窗提示
  ElMessageBox.prompt(h('p', null, ['是否修改账号 ', h('span', {style: 'font-weight: bold'}, item.account), ' 的 私域级别 操作吗？',]), '提示', {
    type: 'warning',
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '请输入新的私域级别',
    inputPattern: /^[0-9]*$/,
  }).then(({value}) => {
    let newValue = parseInt(value) || 0
    if (newValue < 0) {
      ElMessage.error('请输入正确的等级');
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    modifyPrivateLevel({account: item.account, level: newValue}).then(() => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 刷新列表数据
      handleSearch();
    }).finally(() => loading.close())
  }).catch(() => {

  });
};

/** 贡献值释放检测*/
const handleContributionReleaseCheck = () => {
// 弹窗确认提
  ElMessageBox({
    title: '提示',
    message: h('p', null, ['您是否确认进行 ', h('span', {style: 'font-weight: bold; color: var(--el-color-primary);'}, '贡献值释放'), ' 检测操作吗？',]),
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '放弃',
  }).then((action) => {
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    contributionReleaseCheck().then(() => {
      // 提示信息
      ElNotification({title: '成功', message: '已提交到队列中进行操作', type: 'success', duration: 2000})
    }).finally(() => loading.close())
  }).catch(() => {

  });
};
</script>

<style lang="scss" scoped>
.system-user {
  .name-slot {
    display: flex;
    align-items: center;

    .avatar {
      margin-right: 8px;
      background: unset !important;
    }
  }
}
</style>

